package com.zzh.server.config;

import org.omg.IOP.ServiceContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ScopedProxyMode;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import sun.plugin.liveconnect.SecureInvocation;

import java.util.ArrayList;
import java.util.List;

/*
 * @Auther : wenrouyue
 * @Date : 2022/4/8-11:46
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.zzh.server.controller"))
                .paths(PathSelectors.any())
                .build()
                .securityContexts(securityContexts()  )
                .securitySchemes(securitySchemes());
    }
    private List<SecurityContext> securityContexts(){
        ArrayList<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(getContextByPath("/hello.*"));
        return securityContexts;
    }

    private SecurityContext getContextByPath(String path) {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex(path))
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        ArrayList<SecurityReference> securityReferences = new ArrayList<>();
        AuthorizationScope scope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = scope;
        securityReferences.add(new SecurityReference("Authorization",authorizationScopes));
        return securityReferences;
    }

    private List<ApiKey> securitySchemes(){
        //设置请求头信息
        ArrayList<ApiKey> apiKeys = new ArrayList<>();
        ApiKey apiKey = new ApiKey("Authorization", "Authorization", "Header");
        apiKeys.add(apiKey);
        return apiKeys;
    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("yeb接口文档")
                .description("yeb接口文档")
                .contact(new Contact("wenrouyue","http://localhost:8081/doc.html","1547788176@qq.com"))
                .version("1.0")
                .build();
    }
}
